﻿using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Windows;
using System.Windows.Controls;
using SilverlightCalculator.ServiceReference;
using System.Net;
using System.Net.Browser;

namespace SilverlightCalculator
{
    public partial class MainPage : UserControl
    {
        private void Do_Operation(object sender, RoutedEventArgs e)
        {
            flushDisplay = true;
            int number = int.Parse(display.Text);
            string newOperation = (string)((Button)sender).Content;

            if (newOperation == "=")
            {
                ServiceClient proxy = new ServiceClient();
                proxy.CalculateCompleted += new System.EventHandler<CalculateCompletedEventArgs>(proxy_CalculateCompleted);


                switch (previousOperation)
                {
                    case "+":
                        proxy.CalculateAsync(Operation.Add, value, number);
                        break;
                    case "-":
                        proxy.CalculateAsync(Operation.Subtract, value, number);
                        break;
                    case "*":
                        proxy.CalculateAsync(Operation.Multiply, value, number);
                        break;
                    case "/":
                        proxy.CalculateAsync(Operation.Divide, value, number);
                        break;
                }
            }
            else
            {
                previousOperation = newOperation;
                value = number;
            }

        }

        void proxy_CalculateCompleted(object sender, CalculateCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                value = e.Result;
                display.Text = value.ToString();
            }
        }

        #region UI methods

        public MainPage()
        {
            InitializeComponent();
            WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
        }


        private void Add_Didgit(object sender, RoutedEventArgs e)
        {
            if (flushDisplay)
            {
                display.Text = "";
                flushDisplay = false;
            }
            display.Text += ((Button)sender).Content;
        }

        private string previousOperation;
        private int value;
        private bool flushDisplay = false;
        #endregion

    }
}
